/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * email:nur01@qq.com
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, RefreshControl, Image, ListView, ScrollView, StyleSheet, Text, View} from 'react-native';
import StyleUtils from "../../res/styles/StyleUtils";
import ViewUtils from "../../utils/ViewUtils";
import ShopPageListItem from "./ShopPageListItem";
import ConfirmOrderPage from "../confirm/ConfirmOrderPage";
import CommonUtils from "../../common/CommonUtils";
import IparNetwork, {SERVER_TYPE} from "../../httpUtils/IparNetwork";
import I18n from '../../res/language/i18n'
import RegionsIcon from "../../common/RegionsIcon";
import AlertDialog from "../../custom/AlertDialog";


const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
export default class ShopPage extends Component {

    constructor(props) {
        super(props);
        this.cardResultData = [];
        this.iparNetwork = new IparNetwork();
        this.regionsIcon = new RegionsIcon();
        this.commonUtils = new CommonUtils();

        this.selectItem = {order_type: '', data: []};

        this.state = {
            isGoods: false,
            loading: false,
            alertVisible: false,
            cardResultData: [],
            currencyData: '',
            test: false,
            subTotal: 0,
            deleteSelectGoods: null,

            userData: this.props.userData,

        }
    }

    componentDidMount() {


        this.deEmitterUserDataUpdate = DeviceEventEmitter.addListener('upDateUserData', (userData) => {
            if (userData.user_id !== this.state.userData.user_id) {
                this.selectItem.order_type = "";
                this.selectItem.data = [];
                this.setState({
                    subTotal: 0,
                    isGoods: false,
                    cardResultData: [],
                    userData: userData,
                });
            }
        });


        this.deEmitter = DeviceEventEmitter.addListener('isBuyGoods', () => {
            this.onLoadData();
        });

        this.deEmitterPay = DeviceEventEmitter.addListener('isOrder', () => {
            this.selectItem.order_type = "";
            this.selectItem.data = [];
            this.setState({
                subTotal: 0
            })
        });


        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                if (result) {
                    this.setState({
                        currencyData: JSON.parse(result),
                    })
                }
            });

        this.onLoadData();
    }


    componentWillUnmount() {
        this.cardResultData = null;
        this.regionsIcon = null;
        this.selectItem = null;
        this.commonUtils = null;
        this.deEmitter && this.deEmitter.remove();
        this.deEmitterUserDataUpdate && this.deEmitterUserDataUpdate.remove();
        this.deEmitterPay && this.deEmitterPay.remove();
    }


    /**
     * 获取购物车数据
     */
    onLoadData() {
        this.setState({
            loading: true,
        });
        let userId = this.state.userData ? this.state.userData.user_id : '';
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getCartInfo?', 'user_id=' + userId)
            .then((result) => {
                if (result.code === 200 && result.data) {
                    this.cardResultData = result.data;
                    this.setState({
                        isGoods: true,
                        loading: false,
                        cardResultData: result.data,
                    })
                } else {
                    this.setState({
                        loading: false,
                        isGoods: false,
                        // cardResultData: [],
                    });
                }
            })
            .catch((error) => {
                this.setState({
                    loading: false,
                });
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ShopPage-onLoadData-error---', error)
            })
    }


    /**
     *onPressBtn btn 点击
     * */
    submit() {

        if (this.selectItem.data.length <= 0) {
            DeviceEventEmitter.emit('toast', I18n.t('default.chooseProduct'));
            return
        }

        this.props.navigator.push({
            component: ConfirmOrderPage,
            name: 'ConfirmOrderPage',
            params: {
                dataSource: this.selectItem,
                currencyInfo: this.state.currencyData,
            }
        })
    }


    render() {


        let render = (!this.state.isGoods ?//购物车null
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.loading}
                            onRefresh={() => DeviceEventEmitter.emit('isBuyGoods')}
                        />
                    }>
                    <View style={[StyleUtils.flex, {alignItems: 'center', marginTop: 48, padding: 16}]}>
                        {ViewUtils.getTitleView(I18n.t('default.card'), I18n.t('default.cartIsCurrently'),
                            null, null, [StyleUtils.text, {
                                textAlign: 'center',
                                lineHeight: 28
                            }])}
                        {ViewUtils.getButton(I18n.t('default.startShoppingBtn'),
                            () => DeviceEventEmitter.emit('goToPage', 0))}
                    </View></ScrollView> ://购物车not null
                <View style={{height: '100%'}}>
                    <Text style={[styles.noteTv, StyleUtils.smallFont]}>{I18n.t('default.shopNote')}</Text>
                    <ListView
                        refreshControl={
                            <RefreshControl
                                refreshing={this.state.loading}
                                onRefresh={() => DeviceEventEmitter.emit('isBuyGoods')}
                            />
                        }
                        dataSource={ds.cloneWithRows(this.state.cardResultData)}
                        renderRow={(rowData, sectionID, rowID) => this._renderRow(rowData, rowID)}/>


                    {/**bottom*/}
                    <View style={[{paddingRight: 16, paddingLeft: 16,}, StyleUtils.shadowTop]}>
                        <View style={[[StyleUtils.justifySpace, {height: 30}]]}>
                            <Text style={[StyleUtils.smallFont, {height: 26}]}>{I18n.t('default.subtotal')}</Text>
                            <Text style={StyleUtils.smallFont}>
                                {this.state.subTotal + ' ' + this.state.currencyData.currency_code}
                            </Text>
                        </View>
                        {ViewUtils.getButton(I18n.t('default.checkoutBtn'), () => this.submit(), StyleUtils.marginTop)}
                    </View>


                    <AlertDialog
                        contentTv={I18n.t('default.delete')}
                        leftSts={I18n.t('default.delete')}
                        leftBtnOnclick={() => this.deleteGoods()}
                        visible={this.state.alertVisible} requestClose={() => {
                        this.setState({
                            alertVisible: false
                        })
                    }}/>


                </View>
        );
        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                {render}
            </View>
        );
    }

    /**
     * render item title
     * @param rowData
     * @param rowID
     * @returns {*}
     * @private
     */
    _renderRow(rowData, rowID) {
        if (rowData.name === 'mUpdateData') return null;
        let icons = this.regionsIcon.getIcons(rowData.name);


        return (
            <View>
                <View style={[StyleUtils.rowDirection, {
                    alignItems: 'center',
                    paddingLeft: 8,
                    height: 40,
                    backgroundColor: '#e1e1e1'
                }]}>

                    <Image
                        resizeMode="contain"
                        style={{marginLeft: 8, height: 12, width: 20, resizeMode: 'contain'}}
                        source={icons}/>
                    <Text
                        style={[StyleUtils.text, StyleUtils.smallFont, {color: '#333333'}]}>{this.goodsCountry(rowData.name)}</Text>

                </View>
                {rowData.data.map((item, i) => this.renderItems(rowData, rowID, i))}
            </View>
        )
    }

    /*从xxx国家发货*/
    goodsCountry(name) {
        let goodsCountry;
        switch (name) {
            case 'RU':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Russia';
                break;
            case 'CN':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' China';
                break;
            case 'KZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kazakhstan';
                break;
            case 'US':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' United States';
                break;
            case 'KG':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kyrgyzstan';
                break;
            case 'AZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Azerbaijan';
                break;
            default:
                goodsCountry = name;
                break
        }
        return goodsCountry;
    }


    onItemSelect(isChecked, rowData, dataIndex, itemIndex) {
        let newData = this.clone(this.cardResultData);


        for (let i = 0, len = newData.length; i < len; i++) {
            newData[i].is_checked = false;
        }

        if (newData.length > 1 && newData[newData.length - 2].name === 'mUpdateData') {
            newData.splice(newData.length - 2, 1)
        } else {
            newData.push({name: 'mUpdateData', is_checked: false, data: []});
        }

        let newDatum = newData[dataIndex];
        newDatum.is_checked = !newDatum.is_checked;


        newDatum.data[itemIndex].is_checked =
            newDatum.data[itemIndex].is_checked === 1 ? 0 : 1;

        /**
         * select 的 数据
         */
        if (isChecked) {

            //选择别的分类
            if (this.selectItem.order_type !== rowData.name && this.selectItem.data.length > 0) {
                this.selectItem.data = [];
            }

            this.selectItem.order_type = rowData.name;
            this.selectItem.data.push(rowData.data[itemIndex]);
        } else {
            let len = this.selectItem.data.length;
            for (let i = 0; i < len; i++) {
                if (this.selectItem.data[i] && this.selectItem.data[i].cart_id === rowData.data[itemIndex].cart_id) {
                    this.selectItem.data.splice(i, 1)
                }
            }
        }

        let subTotal = this.getSubTotal();


        this.setState({
            subTotal: subTotal,
            test: !this.state.test,
            cardResultData: newData
        });

    }


    /**
     * 获取选择的total amount
     * @returns {number}
     */
    getSubTotal() {
        let _subTotal = 0;
        let len = this.selectItem.data.length;


        let swapAmount = this.state.currencyData.swap_amount;

        for (let i = 0; i < len; i++) {
            let goodsInfo = this.selectItem.data[i];
            let price = (this.commonUtils.getPercentOwnAmount(this.state.userData, goodsInfo, swapAmount,));
            if (price <= 0) {
                price = goodsInfo.goods_pv * swapAmount
            }
            _subTotal += price * goodsInfo.goods_number;
        }
        return (_subTotal).toFixed(1);
    }

    /**
     * clone 方法
     * @param oldArray
     * @returns {*}
     */
    clone(oldArray) {
        if (!oldArray) return;
        let newArray = [];
        for (let i = 0, len = oldArray.length; i < len; i++) {
            newArray.push(oldArray[i])
        }
        return newArray
    }


    /**
     * 删除购物车
     * */
    deleteGoods() {

        if (this.state.deleteSelectGoods === null) return;


        this.setState({
            alertVisible: false,
            loading: true,
        });


        let len = this.selectItem.data.length;
        let cartId = this.state.deleteSelectGoods.cart_id;
        for (let i = 0; i < len; i++) {
            if (this.selectItem.data[i].cart_id === cartId) {
                this.selectItem.data.splice(i, 1);
                this.setState({
                    subTotal: this.getSubTotal(),
                });
                break;
            }
        }

        let formData = new FormData();
        formData.append('cart_id', cartId);
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + "delCart", formData)
            .then((result) => {
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    DeviceEventEmitter.emit('isBuyGoods');
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    this.setState({
                        loading: false,
                    });
                }
            })
            .catch((error) => {
                console.log('ShopPageListItem---editCart--error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                this.setState({
                    loading: false,
                });
            })

    }


    /**
     *renderItems
     * @param rowData
     * @param rowID
     * @param itemIndex
     * @returns {*}
     */
    renderItems(rowData, rowID, itemIndex) {
        let _selectItem = false;
        for (let i = 0, len = this.selectItem.data.length; i < len; i++) {
            if (this.selectItem.data[i].cart_id === rowData.data[itemIndex].cart_id) {
                _selectItem = true;
            }
        }


        return (
            <ShopPageListItem
                updateGoodsInfo={(newGoodsNumber) => {
                    rowData.data[itemIndex].goods_number = newGoodsNumber;
                    this.setState({
                        subTotal: this.getSubTotal(),
                    });
                }}
                deleteGoods={() => this.setState({
                    alertVisible: true,
                    deleteSelectGoods: rowData.data[itemIndex],
                })}
                userData={this.state.userData}
                currency_code={this.state.currencyData}
                dataSource={rowData.data[itemIndex]}
                onPress={(isChecked) => this.onItemSelect(isChecked, rowData, rowID, itemIndex)}
                isChecked={_selectItem}
            />
        );
    }
}
const styles = StyleSheet.create({
    noteTv: {
        fontSize: 16,
        color: 'red',
        marginTop: 30,
        marginBottom: 30,
        textAlign: 'center'
    }
});
